/**
 * 元素宽高、窗口大小变化监听
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { onMounted, onUnmounted, ref } from 'vue';
import { addEventListener, removeEventListener } from '../utils';

/**
 * 使用元素元素宽高变化监听
 * @param selector
 */
export function useResize(selector: string) {
  let el: { [p: string]: any } = {};
  const width = ref(0);
  const height = ref(0);
  let listener: Function;
  if (selector) {
    listener = (e: any) => {
      width.value = el.clientWidth;
      height.value = el.clientHeight;
    };
  } else {
    listener = () => {
      width.value = window.innerWidth;
      height.value = window.innerHeight;
    };
  }

  onMounted(() => {
    if (selector) {
      el = document.querySelector(selector) ?? {};
    }
    listener();
    // @ts-ignore
    addEventListener(window, 'resize', listener);
  });
  // @ts-ignore
  onUnmounted(() => removeEventListener(window, 'resize', listener));

  return { width, height };
}

/**
 * 监听窗口变化
 * @param selector 监听的元素或回调函数
 * @param listener 监听回调函数
 */
export function onResize(selector: string | Function, listener?: Function) {
  onMounted(() => {
    if (typeof selector === 'function') {
      listener = selector;
      listener({});
    } else {
      const el = document.querySelector(selector);
      // @ts-ignore
      selector = listener;
      // @ts-ignore
      listener = (e) => selector(e, el);
      listener({}, el);
    }
    // @ts-ignore
    addEventListener(window, 'resize', listener);
  });
  // @ts-ignore
  onUnmounted(() => removeEventListener(window, 'resize', listener));
}
